package cn.unknowpupil.init.async;


import cn.unknowpupil.init.common.enums.BusinessStatus;
import cn.unknowpupil.init.common.enums.LoginEnum;
import cn.unknowpupil.init.domain.system.SysLogRecord;
import cn.unknowpupil.init.domain.system.SysLoginInfo;
import cn.unknowpupil.init.mapper.system.SysLogRecordMapper;
import cn.unknowpupil.init.mapper.system.SysLoginInfoMapper;
import cn.unknowpupil.init.mapper.system.SysUserMapper;
import cn.unknowpupil.init.utils.DateUtils;
import cn.unknowpupil.init.utils.ServletUtils;
import cn.unknowpupil.init.utils.SpringUtils;
import cn.unknowpupil.init.utils.StringUtils;
import cn.unknowpupil.init.utils.html.IPUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.TimerTask;

/**
 * Created at 2020/10/20 by w10g <br>
 * Initialize AsyncFactory ... <br>
 * 异步工厂（产生任务用）
 *
 * @author unknowpupil
 * @since 0.0.1
 */
public class AsyncFactory {


    private static final Logger logger = LoggerFactory.getLogger(AsyncFactory.class);

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    /**
     * @Async该注解不需要在指定任何bean
     */

    public static TimerTask recordOper(final SysLogRecord operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点

                operLog.setOperLocation(IPUtils.getCityInfo(operLog.getOperIp()));
                operLog.setCreateTime(new Date());
                SpringUtils.getBean(SysLogRecordMapper.class).insert(operLog);
            }
        };
    }

    public static TimerTask updateUser(final Long userId) {
        HttpServletRequest request = ServletUtils.getRequest();
        final String ip = IPUtils.getIp(request);
        return new TimerTask() {
            @Override
            public void run() {
                Date date = new Date();
                logger.info("更新{}用户信息---------->登录IP:{}---------登录时间{}",userId,ip, DateUtils.dateToString(date, DateUtils.DateFormat.ALL_TIME));
                SpringUtils.getBean(SysUserMapper.class).updateByUserId(userId,ip,date);
            }
        };
    }

    /**
     * 记录登录信息
     *
     * @param username  用户名
     * @param loginEnum 状态
     * @param message   消息
     * @param args      列表
     * @return 任务task
     * @Async该注解不需要在指定任何bean
     */


    public static TimerTask recordLoginInfo(final String username, LoginEnum loginEnum, final String message,
                                            final Object... args) {

        HttpServletRequest request = ServletUtils.getRequest();
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        final String ip = IPUtils.getIp(request);

        return new TimerTask() {
            @Override
            public void run() {
                String address =IPUtils.getCityInfo(ip);
                StringBuilder s = new StringBuilder();
                s.append(s);
                s.append(address);

                s.append(StringUtils.getBlock(username));
                s.append(StringUtils.getBlock(loginEnum.code()));
                s.append(StringUtils.getBlock(message));
                // 打印信息到日志
                logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLoginInfo loginInfo = new SysLoginInfo();
                loginInfo.setUserName(username);
                loginInfo.setIpaddr(ip);
                loginInfo.setLoginLocation(address);
                loginInfo.setBrowser(browser);
                loginInfo.setOs(os);
                loginInfo.setMsg(message);
                loginInfo.setLoginTime(new Date());
                loginInfo.setCreateTime(new Date());
                loginInfo.setCreateBy(username);
                // 日志状态
                if (LoginEnum.SUCCESS == loginEnum || LoginEnum.LOGOUT == loginEnum) {
                    loginInfo.setStatus(BusinessStatus.SUCCESS.code());



                } else if (LoginEnum.FAILURE == loginEnum) {
                    loginInfo.setStatus(BusinessStatus.FAILURE.code());
                }
                // 插入数据
                SpringUtils.getBean(SysLoginInfoMapper.class).insert(loginInfo);
                System.out.println("插入数据 记录登录信息");
            }
        };

    }


}
